<!--
  * 采购订单表
  *
  * @Author:    zzw
  * @Date:      2024-10-08 17:37:12
  * @Copyright  jz
-->
<template>
    <a-modal :title="form.id ? '编辑' : '添加'" width="50%" :open="visibleFlag" @cancel="onClose" :maskClosable="false"
        :destroyOnClose="true">
        <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 7 }">

            <a-row>
                <a-col :span="12">
                    <a-form-item label="项目" name="projectId">
                        <a-select v-model:value="form.projectId" :disabled="disabled" :size="size" style="width: 100%"
                            :options="projectOptions"></a-select>
                    </a-form-item>
                </a-col>
                <!-- <a-col :span="12">
                    <a-form-item label="供应商ID" name="supplierId">
                        <a-select v-model:value="form.supplierId" :disabled="disabled"  :size="size" style="width: 100%"
                            :options="subcontractorInfoOptions"></a-select>
                    </a-form-item>
                </a-col> -->
                <a-col :span="12">
                    <a-form-item label="备注" name="remark">
                        <a-input style="width: 100%" :disabled="disabled" v-model:value="form.remark"
                            placeholder="备注" />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <!-- <a-form-item label="订单附件存储路径" name="fileUrl">
                        <a-input style="width: 100%" v-model:value="form.fileUrl" placeholder="订单附件存储路径" />

                    </a-form-item> -->
                    <a-form-item label="订单附件" name="contractAmount">
                        <a-button type="primary" @click="showUploadModal" size="small">
                            <template #icon><cloud-upload-outlined /></template>上传文件
                        </a-button>
                        <a-button :disabled="disabled" type="link" v-if="fileName" @click="viewFile">附件</a-button>
                    </a-form-item>
                    <a-modal v-model:open="uploadModalFlag" title="上传文件" @onCancel="hideUploadModal"
                        @ok="hideUploadModal">
                        <FileUpload :disabled="disabled" list-type="text" :maxUploadSize="5" buttonText="点击上传文件"
                            :defaultFileList="[]" :multiple="true"
                            :folder="FILE_FOLDER_TYPE_ENUM.PURCHASE_ORDER_ATTACHMENT" @change="fileChange" />
                    </a-modal>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="审批人" name="approverId">
                        <a-select style="width: 85%" v-model:value="form.approverId" placeholder="审批人"
                            :allowClear="true">
                            <a-select-option v-for="item in dictValueList" :key="item" :value="item.employeeId">
                                {{ item.actualName }}
                            </a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <!-- <a-col :span="12">
                    <a-form-item label="订单状态" name="orderStatus">
                        <a-select v-model:value="form.orderStatus" :size="size" style="width: 100%"
                            :options="orderStatusOptions"></a-select>
                    </a-form-item>
                </a-col> -->
             
            </a-row>
        </a-form>
        <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :loading="tableLoading"
            :pagination="false" :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }">
            <template #bodyCell="{ text, record, column, index }">
                <template v-if="column.dataIndex === 'index'">
                    {{ index + 1 }}
                </template>
                <template v-if="column.dataIndex === 'goodsId'">
                    <a-select :disabled="disabled" v-model:value="record.goodsId" style="width: 100%"
                        :options="goodsOptions"></a-select>
                </template>
                <template v-if="column.dataIndex === 'quantity'">
                    <a-input-number :disabled="disabled" style="width: 100%" v-model:value="record.quantity" />
                </template>
                <template v-if="column.dataIndex === 'taxRate'">
                    <!-- <a-input-number style="width: 100%" v-model:value="record.taxRate" :min="1" :max="100" :step="0.001"/> -->
                    <a-input-number :disabled="disabled" style="width: 100%" v-model:value="record.taxRate" :min="0"
                        :max="100" :formatter="value => `${value}%`" :parser="value => value.replace('%', '')" />
                </template>
                <template v-if="column.dataIndex === 'action'">
                    <div class="smart-table-operate">
                        <a-button :disabled="disabled" @click="onDelete(index)" danger type="link">删除</a-button>
                    </div>
                </template>
            </template>
        </a-table>
        <div>
            <a-button @click="add" :disabled="disabled" type="dashed">添加采购产品</a-button>
        </div>

        <template #footer>
            <a-space>
                <a-button @click="onClose" v-if="!disabled">取消</a-button>
                <a-button type="primary" v-if="!disabled" @click="onSubmit">保存</a-button>
            </a-space>
        </template>
    </a-modal>
    <a-modal v-model:open="fileopen" title="文件查看" @ok="handleOk" style="width: 1000px; height: 600px">
        <div>
            <!-- <iframe :src="url" width="100%" height="700px" border="0" /> -->
            <iframe :src="fileUrl" style="width: 900px; height: 600px"></iframe>
        </div>
    </a-modal>
</template>
<script setup>
import { reactive, ref, nextTick, onMounted } from 'vue';
import _ from 'lodash';
import { message } from 'ant-design-vue';
import { SmartLoading } from '/@/components/framework/smart-loading';
import { purchaseOrderApi } from '/@/api/business/purchase/index';
import { smartSentry } from '/@/lib/smart-sentry';
import { dictApi } from '/src/api/support/dict-api';
import BooleanSelect from '/@/components/framework/boolean-select/index.vue';
import FileUpload from '/@/components/support/file-upload/index2.vue';
import { FILE_FOLDER_TYPE_ENUM } from '/@/constants/support/file-const';

// ------------------------ 事件 ------------------------

const emits = defineEmits(['reloadList']);


const tableData = ref([])
const columns = ref([
    {
        title: '序号',
        dataIndex: 'index',
        width: 50,
        align: 'center'
    },
    {
        title: '产品ID',
        dataIndex: 'goodsId',
        ellipsis: true,
    },
    {
        title: '产品数量',
        dataIndex: 'quantity',
        ellipsis: true,
    },
    {
        title: '产品税率',
        dataIndex: 'taxRate',
        ellipsis: true,
    },
    {
        title: '操作',
        dataIndex: 'action',
        fixed: 'right',
        width: 90,
    },
]);
// （0待审批、1审批未通过、2待支付、3已支付、4已收货入库）
const orderStatusOptions = ref([
    { value: 0, label: '待审批' },
    { value: 1, label: '审批未通过' },
    { value: 2, label: '待支付' },
    { value: 3, label: '已支付' },
    { value: 4, label: '已收货入库' },
])


const dictValueList = ref([])
async function queryDict() {
  let res = await dictApi.ProjecPersonid();
  dictValueList.value = res.data;
}
// ------------------------ 显示与隐藏 ------------------------
// 是否显示
const visibleFlag = ref(false);
const disabled = ref(false);
function show(rowData, type) {
    queryDict()
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
        Object.assign(form, rowData);
    }
    if (type) {
        disabled.value = true;
    }
    console.log(rowData);
    if (rowData.purchaseOrderGoodsListVOList && rowData.purchaseOrderGoodsListVOList.length) {
        tableData.value = rowData.purchaseOrderGoodsListVOList.map(i => {
            return { ...i }
        })
        tableData.value.forEach(item => item.taxRate = item.taxRate * 100)
    }
    if (form.discountRatio) {
        form.discountRatio = form.discountRatio * 100
    }
    visibleFlag.value = true;
    nextTick(() => {
        formRef.value.clearValidate();
    });
}

function onClose() {
    tableData.value = []
    Object.assign(form, formDefault);
    visibleFlag.value = false;
}

// ------------------------ 表单 ------------------------

// 组件ref
const formRef = ref();

const formDefault = {
    id: undefined,
    projectId: undefined, //订单归属项目ID
    supplierId: undefined, //供应商ID
    remark: undefined, //备注
    fileUrl: undefined, //订单附件存储路径
    // orderStatus: undefined, //订单状态（0待审批、1审批未通过、2待支付、3已支付、4已收货入库）
    discountRatio: undefined, //订单优惠率（存储从 0.0000 到 1.0000 之间的值，表示 0% 到 100%）
    settlementAccount: undefined, //结算账户
    depositPaid: undefined, //已支付订金金额
    orderGoodsListAddForms: [],
    approverId:undefined,
    approverName:undefined
};

let form = reactive({ ...formDefault });

const rules = {
    projectId: [{ required: true, message: '订单归属项目ID 必填' }],
    supplierId: [{ required: true, message: '供应商ID 必填' }],
};

// 点击确定，验证表单
async function onSubmit() {
    let obj = dictValueList.value.filter((e)=>{
        return e.employeeId == form.approverId 
    })
    form.approverName = obj[0].actualName
    try {
        await formRef.value.validateFields();
        save();
    } catch (err) {
        message.error('参数验证错误，请仔细填写表单数据!');
    }
}

// 新建、编辑API
async function save() {
    SmartLoading.show();
    try {
        console.log(tableData.value)
        if (tableData.value && tableData.value.length) {
            if (form.id) {
                form.orderGoodsListUpdateForms = tableData.value.map(item => {
                    item.taxRate = item.taxRate / 100;
                    return item;
                })
            } else {
                form.orderGoodsListAddForms = tableData.value.map(item => {
                    item.taxRate = item.taxRate / 100;
                    return item;
                })
            }


        }

        let obj = { ...form }
        if (obj.discountRatio) {
            obj.discountRatio = obj.discountRatio / 100
        }
        if (form.id) {
            await purchaseOrderApi.update(obj);
        } else {
            await purchaseOrderApi.add(obj);
        }
        message.success('操作成功');

        emits('reloadList');
        onClose();
    } catch (err) {
        smartSentry.captureError(err);
    } finally {
        SmartLoading.hide();
    }
}
// 获取项目下拉
const projectOptions = ref([])
function getProject() {
    purchaseOrderApi.project().then(res => {
        projectOptions.value = res.data.map(element => {
            return {
                label: element.customerName,
                value: element.id
            }
        })
    })
}
// 获取供应商下拉
const subcontractorInfoOptions = ref([])
function getSubcontractorInfo() {
    purchaseOrderApi.subcontractorInfo().then(res => {
        subcontractorInfoOptions.value = res.data.map(element => {
            return {
                label: element.companyName,
                value: element.id
            }
        })
    })
}
const goodsOptions = ref([])
function getGoods() {
    purchaseOrderApi.goods().then(res => {
        console.log(res.data)
        goodsOptions.value = res.data.map(element => {
            return {
                label: element.goodsName,
                value: element.goodsId
            }
        })
    })
}
function add() {
    tableData.value.push({
        goodsId: '',
        quantity: '',
        taxRate: ''
    })
}
function onDelete(index) {
    tableData.value.splice(index, 1)
}
const uploadModalFlag = ref(false);
function showUploadModal() {
    uploadModalFlag.value = true;
}
function hideUploadModal() {
    uploadModalFlag.value = false;
}
const fileUrl = ref('');
const fileKey = ref('');
const fileName = ref('');
const fileChange = async (file) => {
    form.fileUrl = file[0].fileUrl
    fileUrl.value = file[0].fileUrl;
    fileName.value = file[0].fileName;
};
const fileopen = ref(false)
const viewFile = async (fileKey) => {
    // fileopen.value = true;
    window.open(fileUrl.value)
};
onMounted(() => {
    getProject();
    getSubcontractorInfo();
    getGoods();
})
defineExpose({
    show,
});
</script>